package com.my.wangpan.net;

import android.content.Context;
import android.os.AsyncTask;

import com.my.wangpan.LoginActivity;
import com.my.wangpan.util.ExceptionHandler;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.VDiskAPI.Entry;
import com.vdisk.net.exception.VDiskException;
import com.vdisk.net.exception.VDiskFileNotFoundException;
import com.vdisk.net.exception.VDiskFileSizeException;
import com.vdisk.net.exception.VDiskIOException;
import com.vdisk.net.exception.VDiskLocalStorageFullException;
import com.vdisk.net.exception.VDiskParseException;
import com.vdisk.net.exception.VDiskPartialFileException;
import com.vdisk.net.exception.VDiskServerException;
import com.vdisk.net.exception.VDiskUnlinkedException;
import com.vdisk.net.session.AppKeyPair;
import com.vdisk.net.session.Session;

import java.util.List;

/**
 * Created by Administrator on 2016/10/26.
 * 网络请求管理类，统一管理所有的网络请求
 */
public class CloudEngine {
    public static CloudEngine instance;
    VDiskAPI<VDiskAuthSession> mApi;
    public static final int REQ_FILE_LIST = 100;
    public static final int REQ_FILE_DELETE = 101;
    private Context ctx;

    private CloudEngine(Context context){
        ctx = context;
        //在构造方法里面需要初始化
        init(context);
    }

    private void init(Context context) {
        AppKeyPair appKeyPair = new AppKeyPair(LoginActivity.CONSUMER_KEY,LoginActivity.CONSUMER_SECRET);
        /**
         * 正式的环境 VDISK("box")
         * 测试的环境 APP_FOLDER("sandbox")-->支付的（1分钱）
         */
        VDiskAuthSession session = VDiskAuthSession.getInstance(context, appKeyPair, Session.AccessType.VDISK);
        mApi = new VDiskAPI<VDiskAuthSession>(session);
    }

    public static CloudEngine getInstance(Context context){
        if(instance == null){
            synchronized (CloudEngine.class){//表示后面的是只能一个线程来访问,防止线程多次访问导致实例化两次
                if(instance == null){
                    instance = new CloudEngine(context);
                }
            }
        }
        return instance;
    }

    /**得到文件列表*/
    public void getFileList(IDataCallBack dataCallBack,String path,int reqCode){
        new FileListTask(dataCallBack,path,reqCode).execute();
    }

    /**得到文件列表*/
    public void deleteFile(IDataCallBack dataCallBack,String path,int reqCode){
        new FileDeleteTask(dataCallBack,path,reqCode).execute();
    }


    /***
     * 抽取基类
     */
    class FileDeleteTask extends BaseTask{

        String mPath;

        public FileDeleteTask(IDataCallBack dataCallBack,String path,int reqCode) {
            super(dataCallBack,reqCode);
            mPath = path;
            mEvent.reqCode = reqCode;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            //发起删除文件
            try {
                Entry metaData = mApi.delete(mPath);
                mEvent.Data = metaData;
            } catch (VDiskException e) {
                e.printStackTrace();
                updateEvent(ctx,e,mEvent);
            }
            return null;
        }

    }



    class FileListTask extends BaseTask{

        IDataCallBack  mDataCallBack;
        String path;

        public FileListTask(IDataCallBack mDataCallBack,String path,int reqCode) {
            super(mDataCallBack, reqCode);
//            System.out.println("========");
            this.path = path;
            mEvent.reqCode = reqCode;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {//將數據進行初始化，然后再主线程里面进行相应的ui初始化
                Entry metadata = mApi.metadata(path, null, true, false);
                List<Entry> contents = metadata.contents;
                mEvent.Data = contents;
            } catch (VDiskException e) {
                e.printStackTrace();
                updateEvent(ctx,e,mEvent);
            }
            return null;
        }
    }



    //抽取基类
    abstract class BaseTask extends AsyncTask<Void,Void,Void>{

        IDataCallBack  mDataCallBack;
        Event mEvent;

        public BaseTask(IDataCallBack mDataCallBack,int reqCode) {
            super();
            this.mDataCallBack = mDataCallBack;
            mEvent = new Event();
            mEvent.reqCode = reqCode;//对应的数据赋值
        }

        @Override
        protected void onPostExecute(Void aVoid) {//主线程,需要用接口对象传递数据
            mDataCallBack.handleServerData(mEvent.reqCode,mEvent.errCode,mEvent.Data);
            super.onPostExecute(aVoid);
        }
    }


    public static Event updateEvent(Context ctx, VDiskException e, Event event) {
        if (event == null) {
            event = new Event();
        }
        if (e instanceof VDiskServerException) {
            return ExceptionHandler.getErrEvent(ctx, (VDiskServerException) e,
                    event);
        } else if (e instanceof VDiskIOException) {
            event.errCode = ExceptionHandler.VdiskConnectionFailureErrorType;
        } else if (e instanceof VDiskParseException) {
            event.errCode = ExceptionHandler.kVdiskErrorInvalidResponse;
        } else if (e instanceof VDiskLocalStorageFullException) {
            event.errCode = ExceptionHandler.kVdiskErrorInsufficientDiskSpace;
        } else if (e instanceof VDiskUnlinkedException) {
            event.errCode = ExceptionHandler.UNLINKED_ERROR;
        } else if (e instanceof VDiskFileSizeException) {
            event.errCode = ExceptionHandler.FILE_TOO_BIG_ERROR;
        } else if (e instanceof VDiskPartialFileException) {
            event.errCode = ExceptionHandler.PARTIAL_FILE_ERROR;
        } else if (e instanceof VDiskFileNotFoundException) {
            event.errCode = ExceptionHandler.FILE_NOT_FOUND;
        } else {
            event.errCode = ExceptionHandler.OTHER_ERROR;
        }
        return event;
    }

}
